﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using mshtml;

namespace HtmlReader
{
    public sealed class HtmlElementCollection : CollectionBase
    {
        internal HtmlElementCollection(HtmlDocument document)
        {
            Document = document;
        }

        internal HtmlElementCollection(ref IHTMLElementCollection domElements, HtmlDocument document)
        {
            IHTMLElementCollection collection = domElements as IHTMLElementCollection;
            Document = document;
            foreach (IHTMLElement mselement in collection)
            {
                HtmlElement element = document.Dictionary[mselement.GetHashCode()];
                List.Add(element);
            }
        }

        internal HtmlDocument Document { get; private set; }

        public HtmlElement this[int key]
        {
            get
            {
                int index = List[key].GetHashCode();
                return Document.Dictionary[index];
            }
        }

        public HtmlElement GetElementById(string id)
        {
            foreach (HtmlElement element in List)
            {
                if (element.Id == id)
                    return element;
            }

            return null;
        }

        public HtmlElementCollection GetElementsByTagName(string tagName)
        {
            HtmlElementCollection collection = new HtmlElementCollection(Document);
            foreach (HtmlElement element in List)
            {
                if (element.TagName.ToLower() == tagName.ToLower())
                    collection.Add(element);
            }

            if (collection.Count > 0)
                return collection;
            else
                return null;
        }


        public int IndexOf(HtmlElement value)
        {
            return (List.IndexOf(value));
        }

        public int Add(HtmlElement value)
        {
            if (List.Contains(value))
                return -1;
            else
                return (List.Add(value));
        }

        public bool Insert(int index, HtmlElement value)
        {
            if (List.Contains(value))
                return false;

            List.Insert(index, value);
            return true;
        }

        public bool Remove(HtmlElement value)
        {
            if (!List.Contains(value))
                return false;

            List.Remove(value);
            return true;
        }
    }
}
